// pages/getInfo/getInfo.js
import { ajax } from '../../utils/index';

Page({
  /**
   * 页面的初始数据
   */
  data: {
    avatarUrl: "https://mmbiz.qpic.cn/mmbiz/icTdbqWNOwNRna42FI242Lcia07jQodd2FJGIYQfG0LAJGFxM4FbnQP6yfMxBgJ0F3YRqJCJ1aPAK2dQagdusBZg/0",
    nickName: "",
    code: "", // 用于存储从微信获取的 code
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    // 获取微信登录的 code
    wx.login({
      success: res => {
        if (res.code) {
          console.log('res.code：' + res.code);
          this.setData({
            code: res.code
          });
        } else {
          console.log('获取 code 失败：' + res.errMsg);
        }
      },
      fail: err => {
        console.error('登录失败：', err);
      }
    });
  },

  getAvatar(e) {
    const { avatarUrl } = e.detail;
    this.setData({
      avatarUrl
    });
  },

  getNickName(e) {
    const { detail: { value } } = e;
    this.setData({
      nickName: value
    });
  },

  async submit() {
    const { avatarUrl, nickName, code } = this.data;
  
    // 检查必填字段
    if (!avatarUrl || !nickName || !code) {
      wx.showToast({
        title: '您还有信息未填写!',
        icon: 'none'
      });
      return;
    }
  
    // 定义请求URL和数据
    const url = '/api/openid/get_openid';
    const data = { code };
  
    try {
      // 调用后端接口获取 openid, session_key, unionid, token
      const response = await ajax(url, 'GET', data);

      if(response){
        console.log('response',response);
        const { openid, session_key, unionid, token } = response.data.data;

        const userInfo = {
          avatarUrl,
          nickName,
          openid,
          session_key,
          unionid,
          token
        };


        const wxLogin = {
          status : true
        }
        wx.setStorageSync('userInfo', userInfo);
        wx.setStorageSync('wxLogin', wxLogin);
        // console.log('wxLogin', wxLogin);

        wx.switchTab({
          url:'../personal/personal',
          success:()=>{
            // console.log('userInfo',userInfo);
            wx.showToast({
              title: '授权成功',
              icon: 'success'
            })
          },
          fail:()=>{
            wx.showToast({
              title: '授权失败',
              icon: 'none'
            })
          }
          
        })
      }
    } catch (error) {
      console.error('提交失败:',error);
    }
  }
});
